package yartiss.service.model;

import java.util.ArrayList;
import java.util.List;

import javax.swing.table.AbstractTableModel;

import yartiss.engine.simulation.ISchedulingPolicy;
import yartiss.engine.simulation.scheduling.policies.SchedulingPolicyFactory;

@SuppressWarnings("serial")
public class PoliciesTableModel extends AbstractTableModel {

	
	class Entry {
		public String policy ="";
		public String params = "";
	}
	
	private  List<Entry> policies =new ArrayList<Entry>();
	
	@Override
	public int getRowCount() {
		return policies.size();
	}

	@Override
	public int getColumnCount() {
		return 2;
	}

	@Override
	public Object getValueAt(int rowIndex, int columnIndex) {
		Entry  entry = policies.get(rowIndex);
		switch (columnIndex) {
		case 0: return entry.policy;
		case 1 : return entry.params;
		}
		return "";
	}
	
	@Override
	public boolean isCellEditable(int row, int col) {
		return true;
	}
	
	@Override
	public String getColumnName(int col){
		switch (col) {
		case 0: return "Policy name";
		case 1 : return "Parameters";
		}
		return "";
	}
	
	
	@Override
	public Class<?> getColumnClass(int column) {
		switch (column) {
		case 0: return String.class;
		case 1 : return Integer.class;
		}
		return Object.class;
	}
	
	@Override
	public void setValueAt(Object value, int rowIndex, int colIndex) {
		Entry e = policies.get(rowIndex);
		switch (colIndex) {
		case 0:	 e.policy = value.toString(); break;
		case 1:	 e.params = value.toString(); break;
		}
		fireTableDataChanged();
	}
	
	public void addPolicy(String name, String params){
		Entry e = new Entry();
		e.policy = name;
		e.params = params;
		policies.add(e);
		fireTableDataChanged();
	}
	
	public String [] getAvailablePolicies(){
		return SchedulingPolicyFactory.getAvailableSchedulingPoliciesNames();
	}

	public void removeRow(int selectedRow) {
		if(selectedRow >=0 && selectedRow < policies.size() ){
			Entry  entry = policies.get(selectedRow);
			policies.remove(entry);
			fireTableDataChanged();
		}
	}
	
	public ISchedulingPolicy getPolicy(int index, long siDuration){
		Entry row = policies.get(index);
		ISchedulingPolicy policy = SchedulingPolicyFactory.getInstance(row.policy);
		String[] params = row.params.split(" ");
		List<Integer> paramss = new ArrayList<Integer>();
		for (int j = 1; j < params.length; j++) {
			paramss.add(Integer.parseInt(params[j]));
		}
		policy.setParameters(paramss);
		return policy;
	}
	
	
	public List<ISchedulingPolicy> getAll(long siDuration){
		ArrayList<ISchedulingPolicy> all = new ArrayList<ISchedulingPolicy>();
		for (int i = 0; i < getRowCount(); i++) {
			all.add(getPolicy(i, siDuration));
		}
		return all;
	}

}
